import { deepClone } from '@/utils/index'

const componentChild = {}
/**
 * 将./slots中的文件挂载到对象componentChild上
 * 文件名为key，对应JSON配置中的__config__.tag
 * 文件内容为value，解析JSON配置中的__slot__
 */
const slotsFiles = require.context('./slots', false, /\.js$/)
const keys = slotsFiles.keys() || []
keys.forEach(key => {
  // 提取组件名
  const tag = key.replace(/^\.\/(.*)\.\w+$/, '$1')
  // 获得组件default
  const value = slotsFiles(key).default
  componentChild[tag] = value
})

function vModel(dataObject, defaultValue) {
  dataObject.props.value = defaultValue // 修改组件的默认值
  // 设置v-model的input事件
  dataObject.on.input = val => {
    this.$emit('input', val)
  }
}

function mountSlotFlies(h, confClone, children) {
  const childObjs = componentChild[confClone.__config__.tag]
  if (childObjs) {
    Object.keys(childObjs).forEach(key => {
      // 如:key = 'append'
      const childFunc = childObjs[key]
      // 还需要判断__slot__中是否配置了对应的属性
      if (confClone.__slot__ && confClone.__slot__[key]) {
        // children中存储 jsx实现的$createElement构造的对象
        children.push(childFunc(h, confClone, key))
      }
    })
  }
}

function emitEvents(confClone) {
  ['on', 'nativeOn'].forEach(attr => {
    // attr = 'on'
    const eventKeyList = Object.keys(confClone[attr] || {})
    // eventKeyList = [ 'click' ]
    eventKeyList.forEach(key => {
      // key = 'click'
      const val = confClone[attr][key] // val = 'clickTestButton1'
      if (typeof val === 'string') {
        // confClone.on.click = fun // fun $emit a string of onfClone[attr][key]
        confClone[attr][key] = event => this.$emit(val, event)
      }
    })
  })
}

function buildDataObject(confClone, dataObject) {
  Object.keys(confClone).forEach(key => {
    const val = confClone[key]
    if (key === '__vModel__') {
      // 处理 v-model特有的 props.value和input事件
      vModel.call(this, dataObject, confClone.__config__.defaultValue)
    } else if (dataObject[key]) {
      dataObject[key] = { ...dataObject[key], ...val }
    } else {
      dataObject.attrs[key] = val
    }
  })
  // 清理属性
  clearAttrs(dataObject)
}

function clearAttrs(dataObject) {
  delete dataObject.attrs.__config__
  delete dataObject.attrs.__slot__
  delete dataObject.attrs.__methods__
}

function makeDataObject() {
  return {
    attrs: {},
    props: {},
    nativeOn: {},
    on: {},
    style: {}
  }
}

export default {
  props: {
    conf: {
      type: Object,
      required: true
    }
  },
  render(h) {
    // 返回一个空的Data Object 属性结构(https://vuejs.org/v2/guide/render-function.html#The-Data-Object-In-Depth)
    const dataObject = makeDataObject()
    // 保留原始数据
    const confClone = deepClone(this.conf)
    const children = []

    // 如果slots文件夹存在与当前tag同名的文件，则执行文件中的代码，往children中加入如:<template slot="append">元</template>的代码
    mountSlotFlies.call(this, h, confClone, children)

    // 将字符串类型的事件，发送为消息
    emitEvents.call(this, confClone)

    // 将json表单配置转化为vue render可以识别的 “数据对象（dataObject）”
    buildDataObject.call(this, confClone, dataObject)

    // 最后children还需要放入h方法中才能渲染出子元素
    return h(this.conf.__config__.tag, dataObject, children)
  }
}
